import {
  login
} from "@/api";
const CryptoJS = require("crypto-js");

export default {
  data() {
    return {
      userInfo: {
        username: "",
        password: "",
      },
      disabled: false,
    };
  },
  methods: {
    loginForm() {
      let params = this.userInfo;
      let password = params.password;
      if (password) {
        password = CryptoJS.MD5(password).toString();
      }
      login({
          username: params.username,
          password: password
        })
        .then(({
          data
        }) => {
          const {
            code,
            message
          } = data;
          this.$message({
            message: code === "200" ? "登录成功" : message,
            type: code === "200" ? "success" : "error",
            center: true,
            duration: 1000,
          });
          if (code === "200") {
            this.manageLoginSuccess();
          }
        })
        .finally(() => {
          this.disabled = false;
        });
    },
    manageLogin() {
      if (this.userInfo.username != "" && this.userInfo.password != "") {
        this.disabled = true;
        this.loginForm();
      } else {
        if (this.userInfo.username === "") {
          this.$message({
            message: "请输入用户名",
            type: "error",
            center: true,
          });
        } else if (this.userInfo.password === "") {
          this.$message({
            message: "请输入密码",
            type: "error",
            center: true,
          });
        }
      }
    },
    handleLogin(event) {
      if (typeof event === "object" || typeof event === "undefined") {
        if (event.keyCode === 13) {
          this.manageLogin();
        }
      } else {
        this.manageLogin();
      }
    },
    manageLoginSuccess() {
      this.$store.dispatch("GetSiteMenu").then(({
        userInfo,
        siteTypes
      }) => {
        if (userInfo && siteTypes && siteTypes.length === 1 && process.env.VUE_APP_FOLDER_NAME !== 'ga') {
          const sites = siteTypes[0].sites || [];
          // 如果不是平台管理员，所拥有的应用只有一个，而且不是应用的管理员
          if (
            userInfo.isPlatformManager === false &&
            sites.length === 1 &&
            sites[0].isSiteManager === false
          ) {
            this.toSingleApp(sites[0].tokenUrl);
            return;
          }
        }
        this.$router.push({
          name: "switchSite"
        });
      });
    },
    toSingleApp(url) {
      const path = window.location.origin + "/oauth2" + url;
      const host = window.location.hostname;
      const protocol = document.location.protocol;
      const newPath = path + "?prefixUrl=" + protocol + "//" + host;
      window.open(newPath, "_blank");
    },
  },
};